package com.example.jxauflea.service.impl;

import com.example.jxauflea.config.OSSProperties;
import com.example.jxauflea.mapper.UserMapper;
import com.example.jxauflea.pojo.Address;
import com.example.jxauflea.pojo.GoodsImgPO;
import com.example.jxauflea.pojo.UserPO;
import com.example.jxauflea.redis.MessageRedis;
import com.example.jxauflea.service.UserService;
import com.example.jxauflea.util.Context;
import com.example.jxauflea.util.JxauFleaUtil;
import com.example.jxauflea.util.ResultEntity;
import com.example.jxauflea.util.Sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author chenzouquan
 */
@Service
public class UserServiceImpl implements UserService {
    private static MessageRedis messageRedis = new MessageRedis();

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OSSProperties ossProperties;

    @Override
    public ResultEntity<Object> userLogin(String username, String password) {
        if (username.isEmpty() || password.isEmpty()){
            return ResultEntity.falseWithoutData("用户或者密码为空");
        }else{
            UserPO userPO = userMapper.loginOneUser(username, password);
            if (userPO == null){
                return ResultEntity.falseWithoutData("用户名或者密码错误");
            }else{
                if (userPO.getHistoryOpen() == 0){
                    userPO.setHistoryOpenBool(false);
                }else if (userPO.getHistoryOpen() == 1){
                    userPO.setHistoryOpenBool(true);
                }
                Address mu = userPO.getAddressInfo();
                mu.setAddressDetail(userPO.getAddress());
                mu.setName(userPO.getRname());
                mu.setTel(userPO.getPhone());
                return ResultEntity.successWithData(userPO);
            }
        }
    }

    @Override
    public ResultEntity<Object> userAdd(String username, String password) {
        if (username.isEmpty() || password.isEmpty()){
            return ResultEntity.falseWithoutData("用户或者密码为空");
        }else{
            UserPO userPO = new UserPO();
            userPO.setUserId(UUID.randomUUID().toString().replace("-", ""));
            userPO.setUserName(username);
            userPO.setPassword(password);
            userPO.setImgUrl(Context.INFO_IMAGE);
            userPO.setHistoryOpen(0);
            userPO.setHistoryOpenBool(false);
            userPO.setState(3);
            userPO.setModifiedTime(new Date());
            Address mu = userPO.getAddressInfo();
            mu.setAddressDetail(userPO.getAddress());
            mu.setName(userPO.getRname());
            mu.setTel(userPO.getPhone());
            try{
                int count = userMapper.addUser(userPO);
                if (count != 1){
                    return ResultEntity.falseWithoutData("用户注册失败");
                }else{
                    return ResultEntity.successWithData(userPO);
                }
            }catch (Exception e){
                return ResultEntity.falseWithoutData("用户名已经存在");
            }

        }
    }

    @Override
    public synchronized ResultEntity<String> userSendMessage(String phone) {
        String code = UUID.randomUUID().toString().substring(0, 5);
        String json = Sample.sendMessage(phone, code);
        if ("error".equals(json)){
            return ResultEntity.falseWithoutData("error");
        }else{
            return messageRedis.addOneMessage(phone, code);
        }
    }

    @Override
    public ResultEntity<String> verifySMS(String phone, String code) {
        return messageRedis.deleteOneMessage(phone,code);
    }

    @Override
    public ResultEntity<String> updatePassword(String phone,String password) {
        int count  = userMapper.updatePassWord(phone,password);
        if (count != 1){
            return ResultEntity.falseWithoutData("密码失败");
        }else{
            return ResultEntity.successWithData("密码修改成功");
        }
    }

    @Override
    public ResultEntity<String> updateUser(HashMap<String, String> userMap, MultipartFile file,boolean flag) {
        UserPO userPO = new UserPO();
        if (flag){
            try {
                ResultEntity<String> stringResultEntity = JxauFleaUtil.uploadFileToOss(ossProperties.getEndPoint(),
                        ossProperties.getAccessKeyId(),
                        ossProperties.getAccessKeySecret(),
                        file.getInputStream(),
                        ossProperties.getBucketName(),
                        ossProperties.getBucketDomain(),
                        file.getOriginalFilename());
                if(ResultEntity.SUCCESS.equals(stringResultEntity.getResult())){
                    // 如果上传成功，则保存路径
                    userPO.setImgUrl("http://"+stringResultEntity.getData());
                }else{
                    return ResultEntity.falseWithoutData("图片信息上传失败！");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return ResultEntity.falseWithoutData(e.getMessage());
            }
        }
        userPO.setUserId(userMap.get("userId"));
        userPO.setUserName(userMap.get("username"));
        userPO.setRname(userMap.get("name"));
        userPO.setPassword(userMap.get("password"));
        if (userMap.get("historyOpen") != null && "false".equals(userMap.get("historyOpen") )){
            userPO.setHistoryOpen(0);
        }else if (userMap.get("historyOpen") != null && "true".equals(userMap.get("historyOpen"))){
            userPO.setHistoryOpen(1);
        }
        userPO.setModifiedTime(new Date());
        userPO.setAddress(userMap.get("detail"));
        userPO.setEmail(userMap.get("email"));
        userPO.setGender(userMap.get("sex"));
        userPO.setPhone(userMap.get("tel"));
        userPO.setQqNumber(userMap.get("qqNumber"));
        if (userMapper.updateUser(userPO) == 1){
            return ResultEntity.successWithoutData();
        }else {
            return ResultEntity.falseWithoutData("修改失败");
        }
    }

    @Override
    public ResultEntity<UserPO> getOneUser(String userId) {
        UserPO userPO =  userMapper.selectOneUser(userId);
        if (userPO.getHistoryOpen() == 0){
            userPO.setHistoryOpenBool(false);
        }else if (userPO.getHistoryOpen() == 1){
            userPO.setHistoryOpenBool(true);
        }
        return ResultEntity.successWithData(userPO);
    }
}
